package top.kaoshanji.ch04;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

/**
 * 代码清单 ch04-03：服务器套接字示例(4.2.1节)
 * 1、首先启动程序
 * 2、然后在命令窗口输入： telnet localhost 8189
 * 3、输入什么就会返回什么
 * 4、输入 BYE 可以断开连接，停止程序
 * author kaoshanji
 * ^_^
 * create time 2024/12/7 19:15
 */
public class EchoServer {

    private static final Logger logger = LogManager.getLogger(EchoServer.class);

    static final int URL_PORT = 8189;

    public static void main(String[] args) throws IOException {
        logger.info("...代码清单 ch04-03：服务器套接字示例(4.2.1节)...");

        // 服务端Socket
        try (var s = new ServerSocket(URL_PORT)) {

            // 等待客户端连接
            try (Socket incoming = s.accept()) {
                InputStream inputStream = incoming.getInputStream();
                OutputStream outputStream = incoming.getOutputStream();

                try (var in = new Scanner(inputStream, StandardCharsets.UTF_8)){
                    var out = new PrintWriter(new OutputStreamWriter(outputStream, StandardCharsets.UTF_8), true);

                    out.println("Hello! Enter BYE to exit.");

                    var done = false;
                    while (!done && in.hasNextLine()) {
                        String line = in.nextLine();
                        out.println("Echo: " + line);
                        if (line.trim().equals("BYE")) {
                            done = true;
                        }
                    }

                    if (done) {
                        incoming.close();
                    }

                }
            }
        }

    }

}
